package com.controller;

import com.service.BookService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BookAndAuthorRelationServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null) {
            req.getRequestDispatcher("/BookAndAuthor.jsp").forward(req, resp);
        }
        if ("add".equals(method)) {
            int bookId = Integer.parseInt(req.getParameter("bookId"));
            int authorId = Integer.parseInt(req.getParameter("authorId"));

            BookService bookService = new BookService();
            boolean flag = bookService.addRelation(authorId, bookId);
            if (flag) {
                req.setAttribute("message", "绑定关系成功");
                req.setAttribute("requestURI", req.getContextPath() + "/Book");
                req.getRequestDispatcher("/info.jsp").forward(req, resp);
            } else {
                req.setAttribute("message", "绑定关系失败！！！！");
                req.setAttribute("requestURI", req.getContextPath() + "/BookAndAuthor");
                req.getRequestDispatcher("/info.jsp").forward(req, resp);
            }
            return;
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
